package ycl.common.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 处理feign调用丢失cookie拦截器
 *
 * @author ycl
 * @date 2022/6/18 0018 12:27:08
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

	private static final String FEIGN = "feign";
	private static final String COOKIE = "Cookie";

	@Override
	public void apply(RequestTemplate template) {
		HttpServletRequest request = getHttpServletRequest();
		if (request == null)
			return;
		template.header(FEIGN, FEIGN);
		template.header(COOKIE, request.getHeader(COOKIE));
	}

	/**
	 * RequestContextHolder从当前线程中获取请求，又用了线程副本
	 */
	private HttpServletRequest getHttpServletRequest() {
		try {
			return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
		} catch (Exception e) {
			return null;
		}
	}
}
